﻿/* Copyright (C) 2013 Interactive Brokers LLC. All rights reserved. This code is subject to the terms
 * and conditions of the IB API Non-Commercial License or the IB API Commercial License, as applicable. */

#include "StdAfx.h"

#include <stdio.h>
#include <stdlib.h>

#include <chrono>
#include <thread>
#include <fstream>
#include <sstream>

#include "TestCppClient.h"
#include "json11.hpp"
using namespace json11;

const unsigned MAX_ATTEMPTS = 50000;
const unsigned SLEEP_TIME = 10;

#define CONFIG_FILE    "./config.json"

void read_config_file(std::string& content)
{
	std::ifstream fin(CONFIG_FILE);
	std::stringstream buffer;
	buffer << fin.rdbuf();
	content = buffer.str();
	fin.close();
}

/* IMPORTANT: always use your paper trading account. The code below will submit orders as part of the demonstration. */
/* IB will not be responsible for accidental executions on your live account. */
/* Any stock or option symbols displayed are for illustrative purposes only and are not intended to portray a recommendation. */
/* Before contacting our API support team please refer to the available documentation. */
int main(int argc, char** argv)
{
	std::string json_config;
	read_config_file(json_config);
	std::string err_msg;
	Json l_json = json11::Json::parse(json_config, err_msg, JsonParse::COMMENTS);
	if (err_msg.length() > 0) {
		printf("Json parse fail, please check your setting!");
		return false;
	}

	const char* host = l_json["HOST"].string_value().c_str();
	unsigned int port = l_json["PORT"].int_value();
	
    printf("%s:%d\n",host,port);
	//const char* connectOptions = argc > 3 ? argv[3] : "";
//	int clientId = 0;
    int clientId = argc>1?atoi(argv[1]):0;

	unsigned attempt = 0;
	printf( "Start of C++ Socket Client Test %u\n", attempt);

	for (;;) {
		++attempt;
		printf( "Attempt %u of %u\n", attempt, MAX_ATTEMPTS);

		TestCppClient client;

		// if( connectOptions) {
		// 	client.setConnectOptions( connectOptions);
		// }
		
		client.connect( host, port, clientId);
		
		while( client.isConnected()) {
            //client.mytest();
			client.processMessages();
            //sleep(1);

		}
		if( attempt >= MAX_ATTEMPTS) {
			break;
		}

		printf( "Sleeping %u seconds before next attempt\n", SLEEP_TIME);
		std::this_thread::sleep_for(std::chrono::seconds(SLEEP_TIME));
	}

	printf ( "End of C++ Socket Client Test\n");
}

